package com.ziki.account.component;

import com.ziki.account.config.SmsProperties;
import com.ziki.common.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author tianyi
 * @since 2023-02-22 21:50
 */
@Component
@EnableConfigurationProperties(value = SmsProperties.class)
@Slf4j
public class SmsComponent {
    /*
     * 发送地址
     * */
    private static final String URL_PATTERN = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsProperties smsProperties;

    /*
     * 发送短信验证码
     * */
    public void send(String to, String templateId, String value) {
        long beginTime = CommonUtil.getCurrentTimestamp();
        String url = String.format(URL_PATTERN, to, templateId, value);

        HttpHeaders headers = new HttpHeaders();
        //最后在header中的格式（中间是英文空格）为Authorization
        headers.set("Authorization", "APPCODE " + this.smsProperties.getAppCode());
        HttpEntity<Object> entity = new HttpEntity<>(headers);
        // 发送一个短信
        // ResponseEntity<String> response = this.restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        String resp = "org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: \"{\"data\":{},\"msg\":\"短信模板未审核,不能发送短信\",\"success\":false,\"code\":999,\"charge\":false}\"";
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long totalTime = CommonUtil.getCurrentTimestamp() - beginTime;
        log.info("耗时:[{}ms], url:[{}],body:[{}]", totalTime, url, resp);
        log.info("发送短信成功");
        // if (response.getStatusCode() == HttpStatus.OK) {
        // } else {
        //     log.info("发送短信失败:[{}]", response.getBody());
        // }
    }
}
